 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.rca.dto.in.UserDto;
import com.zdkj.subway.rca.entity.SwCkOthenTicketreturn;
import com.zdkj.subway.rca.entity.SwCkOthenTicketreturnLog;
import com.zdkj.subway.rca.entity.SwCkOthenTicketreturnTmp;
import com.zdkj.subway.rca.mapper.SwCkOthenTicketreturnTmpMapper;
import com.zdkj.subway.rca.service.SwCkOthenTicketreturnLogService;
import com.zdkj.subway.rca.service.SwCkOthenTicketreturnService;
import com.zdkj.subway.rca.service.SwCkOthenTicketreturnTmpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 其他运营商单程票退换票临时表
 *
 * @author stw
 * @date 2020-12-31 19:31:38
 */
@Service
public class SwCkOthenTicketreturnTmpServiceImpl extends ServiceImpl<SwCkOthenTicketreturnTmpMapper, SwCkOthenTicketreturnTmp> implements SwCkOthenTicketreturnTmpService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwCkOthenTicketreturnTmpServiceImpl.class);
    private String parsePattern = "yyyy-MM-dd HH:mm:ss";
    @Autowired
    private SwCkOthenTicketreturnService swCkOthenTicketreturnService;

    @Autowired
    private SwCkOthenTicketreturnLogService swCkOthenTicketreturnLogService;

    @Override
    public Boolean saveBatchWithExcel(final File excelFile) throws Exception {

        List<Map<String,String>> lineMap = this.baseMapper.selectLineMap();
        //List<Map<String,String>> stationMap = this.baseMapper.selectStationMap();
        List<Map<String,String>> serviceOrgItemMap = swCkOthenTicketreturnService.selectServiceOrgItemMap();
        List<Map<String,String>> paymentMethod = swCkOthenTicketreturnService.selectPaymentMethodItemMap();
        List<SwCkOthenTicketreturnTmp> listDb = new ArrayList<>();

        for(int n = 0; n < 2; n++) {//只有两个sheet
            List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet(n).headRowNumber(1).doReadSync();
            if (CollectionUtil.isNotEmpty(listMap)) {
                Map<Integer, String> integerStringMap = listMap.get(0);
                String lineCode = getLineCode(lineMap,integerStringMap.get(1));
                String lineName = integerStringMap.get(1);

                String reportTypeTmp = integerStringMap.get(4);//退换票类型 1：正常情况退票 2：特殊情况退票
                Map<String,String> reportTypeMap = swCkOthenTicketreturnService.selectReportTypeMap(reportTypeTmp);

                for (int m = 3; m < listMap.size(); m++) { //第五行开始读数据
                    Map<Integer, String> data = listMap.get(m);
                    // 返回每条数据的键值对 表示所在的列 和所在列的值
                    LOGGER.info("读取到数据:{}", JSON.toJSONString(data));
                    if(StringUtils.isEmpty(data.get(1))){ //获取日期
                        break;
                    }

                    SwCkOthenTicketreturnTmp tmpObj = new SwCkOthenTicketreturnTmp();

                    tmpObj.setStatisticsDateTmp(data.get(1));//日期
                    tmpObj.setLineCode(lineCode);
                    tmpObj.setLineCodeTmp(lineName);
                    tmpObj.setSaleStationTmp(data.get(2));
                    tmpObj.setServiceOrgTmp(data.get(3));
                    tmpObj.setSalePaymentmethodTmp(data.get(4));
                    tmpObj.setReturnStationTmp(data.get(5));
                    tmpObj.setMoneyTmp(data.get(6));
                    tmpObj.setReturnPaymentmethodTmp(data.get(7));
                    tmpObj.setRemark(data.get(8));
                    tmpObj.setReportType(reportTypeMap.get("value"));
                    tmpObj.setReportTypeTmp(reportTypeTmp);

                    if (StringUtils.isEmpty(tmpObj.getStatisticsDateTmp())) {
                        continue;
                    }
                    if (!parseDate(tmpObj.getStatisticsDateTmp())) {
                        continue;
                    }
                    final SwCkOthenTicketreturnTmp obj = ObjectUtils.getDefaultObj(SwCkOthenTicketreturnTmp.class);
                    BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
                    checkErr(obj,lineMap,null,serviceOrgItemMap,paymentMethod);
                    listDb.add(obj);

                }
            }
        }
        MultipartFileToFile.delteTempFile(excelFile);
        if(!listDb.isEmpty()) {
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("CREATOR_ID", listDb.get(0).getCreatorId());
            this.baseMapper.deleteByMap(columnMap);
            return this.saveBatch(listDb);
        }
        return false;
    }

    private String getLineCode (List<Map<String,String>> lineMap,String lineName) {
        for (Map<String,String> map : lineMap){
            if(lineName.equals(map.get("NAME"))){
                return map.get("CODE");
            }
        }
        return "";
    }

    private String getStationCode (List<Map<String,String>> stationMap,String stationName,String lineCode) {
        for (Map<String,String> map : stationMap){
            if(stationName.equals(map.get("NAME")) && lineCode.equals(map.get("LINE_CODE"))){
                return map.get("CODE");
            }
        }
        return "";
    }
    private String getPaymentMethodItemCode (List<Map<String,String>> paymentMethodMap,String paymentMethodItemName) {
        if(StringUtils.isNotEmpty(paymentMethodItemName)){
            for (Map<String,String> map : paymentMethodMap){
                if(paymentMethodItemName.equals(map.get("label"))){
                    return map.get("value");
                }
            }
        }
        return "";
    }
    private String getServiceOrgItemCode (List<Map<String,String>> serviceOrgItemMap,String serviceOrgItemName) {
        if(StringUtils.isNotEmpty(serviceOrgItemName)){
            for (Map<String,String> map : serviceOrgItemMap){
                if(serviceOrgItemName.equals(map.get("serviceName"))){
                    return map.get("serviceId");
                }
            }
        }
        return "";
    }
    private void checkErr(SwCkOthenTicketreturnTmp obj, List<Map<String,String>> lineMap,List<Map<String,String>> stationMap,List<Map<String,String>> serviceOrgItemMap,List<Map<String,String>> paymentMethodMap) {
        //更新字段
        try {
            String statisticsDateTmp = obj.getStatisticsDateTmp();
            Date statisticsDate = DateUtils.parseDate(statisticsDateTmp, parsePattern);
            obj.setStatisticsDate(statisticsDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        } catch (Exception e) {
            obj.setErrMsg("退票日期 为空或格式错误");
        }

        if(StringUtils.isNotEmpty(obj.getLineCodeTmp())){
            String lineCode = getLineCode(lineMap,obj.getLineCodeTmp());
            if(StringUtils.isNotEmpty(lineCode)){
                obj.setLineCode(lineCode);
            } else {
                obj.setErrMsg("线路名称 为空或不规范");
            }

        } else {
            obj.setErrMsg("线路名称 为空");
        }
        /* 不验证车站
        if(StringUtils.isNotEmpty(obj.getStationCodeTmp()) && StringUtils.isNotEmpty(obj.getLineCode())){
            String stationCode = getStationCode(stationMap,obj.getStationCodeTmp(),obj.getLineCode());
            if(StringUtils.isNotEmpty(stationCode)){
                obj.setStationCode(stationCode);
            } else {
                obj.setErrMsg("车站名称 为空或不规范");
            }
        } else {
            obj.setErrMsg("车站名称 为空");
        }*/
        if(StringUtils.isNotEmpty(obj.getServiceOrgTmp())){
        	obj.setServiceOrg(obj.getServiceOrgTmp());
            String serviceItem = getServiceOrgItemCode(serviceOrgItemMap,obj.getServiceOrgTmp());
            if(StringUtils.isNotEmpty(serviceItem)){
                obj.setServiceOrg(serviceItem);
            } 
        } else {
            obj.setErrMsg("归属运营商 为空");
        }
        //增加退票支付方式验证
        if(StringUtils.isNotEmpty(obj.getSalePaymentmethodTmp())){//售卖支付方式
        	obj.setSalePaymentmethod(obj.getSalePaymentmethodTmp());
            String paymethodItem = getPaymentMethodItemCode(paymentMethodMap,obj.getSalePaymentmethodTmp());
            if(StringUtils.isNotEmpty(paymethodItem)){
                obj.setSalePaymentmethod(paymethodItem);
            } 
        } else {
            obj.setErrMsg("购票支付方式 为空");
        }
       //增加退票支付方式验证
        if(StringUtils.isNotEmpty(obj.getReturnPaymentmethodTmp())){//售卖支付方式
        	obj.setReturnPaymentmethod(obj.getReturnPaymentmethodTmp());
            String paymethodItem = getPaymentMethodItemCode(paymentMethodMap,obj.getReturnPaymentmethodTmp());
            if(StringUtils.isNotEmpty(paymethodItem)){
                obj.setReturnPaymentmethod(paymethodItem);
            } 
        } else {
            obj.setErrMsg("退票支付方式 为空");
        }

       try {
            BigDecimal num = new BigDecimal("100");

            String itemMoneyTmp = obj.getMoneyTmp();
            BigDecimal itemMoney = new BigDecimal(itemMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            itemMoney = itemMoney.multiply(num);
            obj.setMoney(itemMoney.longValue());

        } catch (Exception e) {
            obj.setErrMsg("金额 为空或格式错误");
        }
       //车站暂时只存名称，不用单独再转换
       obj.setSaleStation(obj.getSaleStationTmp());
      
       obj.setReturnStation(obj.getReturnStationTmp());


        //判断数据是否存在,是否有必要验证，------------？？？？？？？？？？？？？？？       
        SwCkOthenTicketreturn swCkOthenTicketreturn = new SwCkOthenTicketreturn();
        BeanUtils.copyProperties(obj, swCkOthenTicketreturn, "deptId","creatorId","creatorName","createTime");
        int cont = swCkOthenTicketreturnService.count(Wrappers.query(swCkOthenTicketreturn));
        if (cont > 0) {
            obj.setErrMsg("数据已存在");
        }
    }



    private boolean parseDate(String string) {
        boolean convertSuccess = true;
        if (string == null) {
            return false;
        }

        try {
            DateUtils.parseDate(string, parsePattern);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }

    @Override
    public void saveBatchWithExcelOk(UserDto user) {
        List<Map<String,String>> mapList = this.baseMapper.selectMaxMinStatisticsDate(user.getId());
        if(CollectionUtil.isEmpty(mapList)) {
            return;
        }
        String uuid = UUID.randomUUID().toString().toLowerCase();
        Map<String, String> map1 = mapList.get(0);
        String reportType = map1.get("reportType");
        for (Map<String, String> map : mapList) {
            String lineCode = map.get("lineCode");
            String minStatisticsDate = map.get("minStatisticsDate");
            String maxStatisticsDate = map.get("maxStatisticsDate");

            SwCkOthenTicketreturnLog swCkOthenTicketreturnLog = new SwCkOthenTicketreturnLog();
            swCkOthenTicketreturnLog.setBeginTime(LocalDate.parse(minStatisticsDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            swCkOthenTicketreturnLog.setEndTime(LocalDate.parse(maxStatisticsDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            swCkOthenTicketreturnLog.setSubmitPersonId(user.getId());
            swCkOthenTicketreturnLog.setSubmitPersonCode(user.getUserCode());
            swCkOthenTicketreturnLog.setSubmitPersonName(user.getNikeName());
            swCkOthenTicketreturnLog.setCreatorId(user.getId());
            swCkOthenTicketreturnLog.setDeptId(user.getDeptId());
            swCkOthenTicketreturnLog.setCreatorName(user.getNikeName());
            swCkOthenTicketreturnLog.setUuid(uuid);
            swCkOthenTicketreturnLog.setLineCode(lineCode);//线路
            swCkOthenTicketreturnLog.setReportType(reportType);//退换票类型

            swCkOthenTicketreturnLogService.save(swCkOthenTicketreturnLog);
            //导入先删除
            this.baseMapper.deleteBatchWithExcelOk(user.getId(),lineCode,reportType);
        }

        //导入先删除再添加包括重复的
        this.baseMapper.saveBatchWithExcelOkRepeat(user.getId(),uuid);
        //this.baseMapper.saveBatchWithExcelOk(user.getId(),uuid);
        saveBatchWithExcelCancel(user.getId());
    }

    @Override
    public void saveBatchWithExcelCancel(Integer creatorId) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("CREATOR_ID", creatorId);
        this.baseMapper.deleteByMap(columnMap);
    }
	

}
